package com.heima.sjms.工厂.手写IOC;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jack
 * @data 2023 10:40
 */

public class MySpringIOC {

    private static Map<String, Object> ioc;

    static {
        //1. 实例化容器
        System.out.println("自定义IOC容器开始启动....");
        ioc = new HashMap<>();
        try {
            //2. 进行bean的扫描
            //2.1 拿到当前包下的所有类文件
            String packageName = MySpringIOC.class.getPackage().getName();
            String packagePath = packageName.replace(".", "/");
            File classPath = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath());
            String filePath = classPath + "/" + packagePath;

            File folder = new File(filePath);
            File[] files = folder.listFiles(file -> file.isFile() && file.getName().endsWith(".class"));
            List<Class<?>> classes = new ArrayList<>();

            for (File file : files) {

                // 将文件名转换为类名
                String fileName = file.getName();
                String className = packageName + "." + fileName.substring(0, fileName.length() - 6);

                // 加载类，并将类的字节码文件对象加入到集合中
                Class<?> clazz = Class.forName(className);

                //判断当前类上有没有@Service注解
                boolean hasService = clazz.isAnnotationPresent(Service.class);
                if (hasService) {
                    classes.add(clazz);
                }

            }

            // 输出所有类的字节码文件对象
            for (Class<?> clazz : classes) {
                //实例化bean
                Object bean = clazz.newInstance();
                //3. 进行容器的bean的初始化
                ioc.put(clazz.getSimpleName(),bean);
            }

            System.out.println("ioc 容器初始化完毕=============>");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static Object getBean(String beanName){
        return ioc.get(beanName);
    }

    public static void main(String[] args) {
        Object userServiceImpl1 = ioc.get("UserServiceImpl1");
        System.out.println("userServiceImpl1 = " + userServiceImpl1);

    }


}
